package com.itheima.web.controller;

import com.itheima.domain.SysLog;
import com.itheima.service.ISysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


@Component
@Aspect//定义切面类
public class LogAop {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ISysLogService sysLogService;

    private Date visitTime;//开始时间


    //定义切面表达式
    @Pointcut("execution(* com.itheima.web.controller.*.*(..))")
    public void logPointcut() {
    }


    //定义前置通知——主要获取开始时间
    @Before("logPointcut()")
    public void before(JoinPoint jp) {
        visitTime = new Date();
    }

    //定义后置通知
    @AfterReturning("logPointcut()")
    public void afterReturning(JoinPoint jp) {
        try {
            //1、获取访问时长
            long time = new Date().getTime() - visitTime.getTime();

            //2、获取访问方法

            //2.1、获取执行的类名
            String typeName = jp.getSignature().getDeclaringTypeName();
            //2.2、获取执行的方法名
            String methodName = jp.getSignature().getName();

            //3、获取访问路径
            String url = request.getRequestURI();

            //4、获取访问的ip
            String ip = request.getRemoteAddr();

            //5、获取当前操作的用户
            //可以通过securityContext获取，也可以从request.getSession()中获取
            SecurityContext context = SecurityContextHolder.getContext();
            User user = (User) context.getAuthentication().getPrincipal();
            String username = user.getUsername();

            //将日志相关信息封装到SysLog对象
            SysLog sysLog = new SysLog();
            sysLog.setExecutionTime(time);//执行时长
            sysLog.setIp(ip);
            sysLog.setMethod("[类名]" + typeName + "[方法名]" + methodName);
            sysLog.setUrl(url);
            sysLog.setUsername(username);
            sysLog.setVisitTime(visitTime);

            //6、调用service存储日志信息
            sysLogService.insertSysLog(sysLog);
        } catch (Exception e) {
            System.out.println("*******************" + e.getMessage());
        }


    }


}
